<!-- 单选框组件 -->
<template>
  <van-field
    v-if="!readonly"
    name="radio"
    :required="required"
    :label="labelText"
    :rules="[{ required: required, message: message }]"
  >
    <template #input>
      <van-radio-group
        @change="changeGroup"
        v-model="filedModelValue"
        :disabled="disabled"
        :direction="direction"
      >
        <van-radio v-for="(item, i) in state.radioList" :key="i" :name="item.value">
          {{ item.text }}
        </van-radio>
      </van-radio-group>
    </template>
  </van-field>
  <!-- 详情只读模式 -->
  <van-field
    v-else
    readonly
    :label="labelText"
    :placeholder="labelText"
    v-model="groupRadioText"
  />
</template>

<script setup>
import { ref, reactive, watch, computed, onBeforeMount } from 'vue'
import { dictStore } from '@/pinia/modules/dict.js'

const emit = defineEmits(['update:value'])

const props = defineProps({
  // label名称
  labelText: {
    type: String,
    default: '单选框'
  },
  // 选择器下拉选项
  radioList: {
    type: Array,
    default: () => [
      { text: '男', value: '1' },
      { text: '女', value: '2' }
    ]
  },
  // 是否必填
  required: {
    type: Boolean,
    default: false
  },
  // 提示语
  message: {
    type: String,
    default: '请选择'
  },
  // 双向绑定的值
  value: {
    type: String,
    default: ''
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  //   排列方式 vertical竖向
  direction: {
    type: String,
    default: 'horizontal'
  },
  // readonly true 只读模式 false 表单模式
  readonly: {
    type: Boolean,
    default: false
  },
  code:{
    type: String,
    default: 'SF'
  }
})
const state = reactive({
  radioList: props.radioList
})
const groupRadioText = ref('')
const filedModelValue = ref(props.value)

const groupChecked = computed({
  get() {
    if (props.value) {
      return props.value
    }
    return
  },
  set(newValue) {
    filedModelValue.value = newValue
  }
})

const initCode = () => {
  let target = dictStore().dict.find(item => item.code == props.code)
  console.log(target);
  let arr = []
  if (target && target.children.length > 0) {
    target.children.forEach(item => {
      arr.push({ value: item.code, text: item.name })
    })
  }
  state.radioList = arr
  // keyValue.value = new Date().getTime()
  console.log(arr)
}

// const groupChecked = ref('')

const changeGroup = val => {
  emit('update:value', val)
}

onBeforeMount(()=>{
  if(props.code){
    initCode()
  }
  if (props.value) {
    filedModelValue.value = props.value
    if (props.readonly) {
      let arr = []
      props.value.split(',').map(v => {
        let res = state.radioList.filter(item => {
          return item.value == v
        })
        if(res && res.length > 0){
          arr.push(res[0].text)
        }
        
      })
      groupRadioText.value = arr[0] || ''
    }
  }
})
</script>
<style lang="scss" scoped>
.van-checkbox {
  margin: 5px 12px 5px 0;
}
</style>
